package com.ayoka.ui.assignment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import com.ayoka.Constant;
import com.ayoka.R;
import com.ayoka.adapter.UserPictureAdapter;
import com.ayoka.base.BaseFragment;
import com.ayoka.bean.CourseAssignmentBean;
import com.ayoka.databinding.FragmentCourseAssignmentAppreciateBinding;
import com.ayoka.mvp.CourseAssignmentAppreciateMVP.CourseAssignmentAppreciateModel.ChildPhotoBean;
import com.ayoka.mvp.CourseAssignmentAppreciateMVP.CourseAssignmentAppreciatePresenter;
import com.ayoka.mvp.CourseAssignmentAppreciateMVP.ICourseAssignmentAppreciateView;
import com.ayoka.utils.MediaManager;
import com.ayoka.widget.RecordAudioButton;
import com.jcp.baselibrary.brvah.BaseQuickAdapter;
import com.jcp.baselibrary.permission.MPermission;
import com.jcp.baselibrary.utils.DateUtil;
import com.jcp.baselibrary.utils.SPUtil;
import com.jcp.baselibrary.utils.UIUtils;
import com.jincp.image.compress.ImageCompressListener;
import com.jincp.image.compress.ImageCompressProxy;
import com.jincp.image.load.ImageLoaderProxy;
import com.jincp.image.pick.ImagePicker;
import com.jincp.image.pick.bean.ImageItem;
import com.jincp.image.pick.ui.image.PickImageActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class CourseAssignmentAppreciateFragment extends BaseFragment<FragmentCourseAssignmentAppreciateBinding, CourseAssignmentAppreciatePresenter> implements ICourseAssignmentAppreciateView, RecordAudioButton.IRecordAudioListener {

    public static final int MODE_TEXT = 0;
    public static final int MODE_VOICE = 1;

    public static final long DEFAULT_MAX_RECORD_TIME = 120000;
    public static final long DEFAULT_MIN_RECORD_TIME = 2000;
    protected static final int DEFAULT_MIN_TIME_UPDATE_TIME = 1000;

    public static CourseAssignmentAppreciateFragment newInstance(CourseAssignmentBean courseAssignmentBean) {
        CourseAssignmentAppreciateFragment assignmentFragment = new CourseAssignmentAppreciateFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("CourseAssignmentBean", courseAssignmentBean);
        assignmentFragment.setArguments(bundle);
        return assignmentFragment;
    }

    protected CourseAssignmentBean courseAssignmentBean;

    private int appreciateMode = MODE_TEXT;

    private File audioFile;
    private String audioFileName;
    private long maxRecordTime = DEFAULT_MAX_RECORD_TIME;
    private long minRecordTime = DEFAULT_MIN_RECORD_TIME;
    private long recordTotalTime;
    private long durationTime;
    private Timer timer;
    private TimerTask timerTask;

    private List<ChildPhotoBean> pictureList;
    private UserPictureAdapter adapter;
    private ChildPhotoBean childPhotoBean;

    @Override
    protected void configBundleArguments() {
        courseAssignmentBean = (CourseAssignmentBean) getArguments().getSerializable("CourseAssignmentBean");
    }


    @Override
    public int getContentLayout() {
        return R.layout.fragment_course_assignment_appreciate;
    }

    @Override
    protected void initViews(View view) {
        mDataBinding.ivSwitchMode.setOnClickListener(this);

        mDataBinding.edtNote.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getActivity().invalidateOptionsMenu();
            }
        });

        // 设置录音按钮的监听事件
        mDataBinding.recordAudioButton.setRecordAudioListener(this);
        mDataBinding.llPlayAudio.setOnClickListener(this);
        mDataBinding.ivDeleteVoice.setOnClickListener(this);

        boolean isSwitchButtonOpen = SPUtil.getBoolean(Constant.SWITCH_BUTTON, true);
        mDataBinding.swbSecrecy.setChecked(isSwitchButtonOpen);


    }

    @Override
    public void initData() {
        requestBasicPermission();
        mPresenter.getUserChildPictureListData();
        initTimer();
    }

    @Override
    protected CourseAssignmentAppreciatePresenter getPresenter() {
        return new CourseAssignmentAppreciatePresenter();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mDataBinding.ivPicture) {
            if (MPermission.hasPermissions(getActivity(), BASIC_PERMISSIONS)) {
                ImagePicker.getInstance().clear();
                ImagePicker.getInstance().setCrop(true);
                ImagePicker.getInstance().setFocusWidth((int) UIUtils.getDimensionPixelSize(R.dimen.dp_350));
                ImagePicker.getInstance().setFocusHeight((int) UIUtils.getDimensionPixelSize(R.dimen.dp_250));
                ImagePicker.getInstance().setOutPutX((int) UIUtils.getDimensionPixelSize(R.dimen.dp_350));
                ImagePicker.getInstance().setOutPutY((int) UIUtils.getDimensionPixelSize(R.dimen.dp_250));
                PickImageActivity.start(CourseAssignmentAppreciateFragment.this, PickImageActivity.REQUEST_CODE, PickImageActivity.FROM_LOCAL);
            } else {
                showToast(UIUtils.getString(R.string.need_permission));
            }
        }
        if (view == mDataBinding.ivSwitchMode) {
            if (appreciateMode == MODE_TEXT) {
                mDataBinding.ivSwitchMode.setImageResource(R.mipmap.icon_text_mode);
                mDataBinding.rlVoiceContainer.setVisibility(View.VISIBLE);
                mDataBinding.llVoiceInputLayout.setVisibility(View.VISIBLE);
                mDataBinding.llVoiceShowLayout.setVisibility(View.GONE);
                mDataBinding.edtNote.setVisibility(View.GONE);
                mDataBinding.edtNote.setText("");
                appreciateMode = MODE_VOICE;
            } else {
                mDataBinding.ivSwitchMode.setImageResource(R.mipmap.icon_voice_mode);
                mDataBinding.rlVoiceContainer.setVisibility(View.GONE);
                mDataBinding.edtNote.setVisibility(View.VISIBLE);
                audioFile = null;
                appreciateMode = MODE_TEXT;
            }
            getActivity().invalidateOptionsMenu();
        }
        if (view == mDataBinding.llPlayAudio) {
            final AnimationDrawable animator = (AnimationDrawable) mDataBinding.ivSoundAnimator.getBackground();
            MediaManager.getInstance().setMediaDataSource(getActivity(), audioFileName);
//            MediaManager.getInstance().setPlayMusicCallback(new SimpleMediaPlayListener() {
//                @Override
//                public void getMusicDuration(int duration) {
//                    MediaManager.getInstance().start();
//                }
//
//                @Override
//                public void onMediaPlayStart() {
//                    animator.start();
//                }
//
//                @Override
//                public void onMediaPlayStop() {
//                    animator.stop();
//                }
//
//                @Override
//                public void onMediaPlayCompletion() {
//                    animator.stop();
//                    animator.selectDrawable(0);
//                }
//            });
        }
        if (view == mDataBinding.ivDeleteVoice) {
            mDataBinding.llVoiceShowLayout.setVisibility(View.GONE);
            mDataBinding.llVoiceInputLayout.setVisibility(View.VISIBLE);
            audioFileName = "";
            audioFile = null;
            getActivity().invalidateOptionsMenu();
        }
    }

    public boolean canSubmit() {
        if (mDataBinding == null) return false;
        if (childPhotoBean == null) {
            return false;
        }
        if (appreciateMode == MODE_TEXT) {
            return mDataBinding.edtNote.length() > 0;
        } else {
            return audioFile != null;
        }
    }


    @Override
    public void configCourseAssignmentDetailData(CourseAssignmentBean result) {

    }

    @Override
    public void configUserPictureListData(List<ChildPhotoBean> result) {
        pictureList = result;
        if (result.isEmpty()) {
            mDataBinding.ivPicture.setOnClickListener(this);
        } else {
            childPhotoBean = pictureList.get(pictureList.size() - 1);
            ImageLoaderProxy.getInstance().displayImage(childPhotoBean.ImgUrl, mDataBinding.ivPicture);
            pictureList.add(null);
        }
        mDataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        adapter = new UserPictureAdapter(pictureList);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == adapter.getItemCount() - 1) {
                    if (MPermission.hasPermissions(getActivity(), BASIC_PERMISSIONS)) {
                        ImagePicker.getInstance().clear();
                        ImagePicker.getInstance().setCrop(true);
                        ImagePicker.getInstance().setFocusWidth((int) UIUtils.getDimensionPixelSize(R.dimen.dp_350));
                        ImagePicker.getInstance().setFocusHeight((int) UIUtils.getDimensionPixelSize(R.dimen.dp_250));
                        ImagePicker.getInstance().setOutPutX((int) UIUtils.getDimensionPixelSize(R.dimen.dp_350));
                        ImagePicker.getInstance().setOutPutY((int) UIUtils.getDimensionPixelSize(R.dimen.dp_250));
                        PickImageActivity.start(CourseAssignmentAppreciateFragment.this, PickImageActivity.REQUEST_CODE, PickImageActivity.FROM_LOCAL);
                    } else {
                        showToast(UIUtils.getString(R.string.need_permission));
                    }
                } else {
                    childPhotoBean = (ChildPhotoBean) adapter.getItem(position);
                    ImageLoaderProxy.getInstance().displayImage(childPhotoBean.ImgUrl, mDataBinding.ivPicture);
                }
            }
        });
        mDataBinding.recyclerView.setAdapter(adapter);
        // 更新activity中的menu
        getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onUploadChildPictureSuccess(ChildPhotoBean data) {
        mDataBinding.ivPicture.setOnClickListener(null);
        if (pictureList.isEmpty()) {
            pictureList.add(null);
        }
        adapter.addData(pictureList.size() - 1, data);
        childPhotoBean = data;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PickImageActivity.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                List<ImageItem> selectPic = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (selectPic == null || selectPic.isEmpty()) return;
                File file = new File(selectPic.get(0).path);
                if (file.exists()) {
                    ImageCompressProxy.getInstance().compressImage(selectPic.get(0).path, new ImageCompressListener() {
                        @Override
                        public void onCompressSuccess(List<String> imagePathList) {
                            String newFilePath = imagePathList.get(0);
                            ImageLoaderProxy.getInstance().displayImage(newFilePath, mDataBinding.ivPicture);
                            File newFile = new File(newFilePath);
                            mPresenter.uploadChildPicture(newFile);
                        }

                        @Override
                        public void onCompressFailed(List<String> imagePathList, String msg) {

                        }
                    });
                }
            }
        }
    }

    /**
     * 初始化计时器用来更新倒计时
     */
    private void initTimer() {
        recordTotalTime = 0;
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                // 回到主线程
                UIUtils.postTaskSafely(new Runnable() {
                    @Override
                    public void run() {
                        recordTotalTime += 1000;
                        if (recordTotalTime >= maxRecordTime) {
                            mDataBinding.recordAudioButton.invokeStop();
                            timer.cancel();
                        }
                    }
                });
            }
        };
    }


    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO
    };

    private void requestBasicPermission() {
        MPermission.with(this)
                .setRequestCode(Constant.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    @Override
    public boolean onRecordPrepare() {
        //检查录音权限
        if (!MPermission.hasPermissions(getActivity(), Manifest.permission.RECORD_AUDIO)) {
            MPermission.with(this)
                    .setRequestCode(Constant.BASIC_PERMISSION_REQUEST_CODE)
                    .permissions(Manifest.permission.RECORD_AUDIO)
                    .request();
            return false;
        }
        return true;
    }

    @Override
    public void onRecordStart() {
        mDataBinding.recordAudioWaveView.start();
        initTimer();
        timer.schedule(timerTask, 0, DEFAULT_MIN_TIME_UPDATE_TIME);
    }

    @Override
    public boolean onRecordStop(String audioPath, long duration) {
        timer.cancel();
        mDataBinding.recordAudioWaveView.stop();
        if (recordTotalTime >= minRecordTime) {
            File file = new File(audioPath);
            if (file.exists()) {
                mDataBinding.llVoiceShowLayout.setVisibility(View.VISIBLE);
                mDataBinding.llVoiceInputLayout.setVisibility(View.GONE);
                audioFileName = audioPath;
                audioFile = new File(audioPath);
                durationTime = duration;
                mDataBinding.tvAudioDuration.setText(DateUtil.formatTime(durationTime / 1000));
                getActivity().invalidateOptionsMenu();
            }
        } else {
            showToast("时间过短");
            mDataBinding.tvRecordAudioTips.setText("时间过短，取消录音");
            onRecordCancel();
        }
        return false;
    }

    @Override
    public boolean onRecordCancel() {
        mDataBinding.recordAudioWaveView.stop();
        return false;
    }

    @Override
    public void onSlideTop() {
        mDataBinding.tvRecordAudioTips.setText("松开手指，取消录音");
    }

    @Override
    public void onFingerPress() {
        mDataBinding.tvRecordAudioTips.setText("长按话筒，对孩子说");
    }
}
